package org.jeecg.modules.water.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.water.entity.LwgyJointWater;
import org.jeecg.modules.water.entity.LwgyJointWaterConfiguration;
import org.jeecg.modules.water.entity.LwgyJointWaterDaily;
import org.jeecg.modules.water.service.ILwgyJointWaterConfigurationService;
import org.jeecg.modules.water.service.ILwgyJointWaterDailyService;
import org.jeecg.modules.water.service.ILwgyJointWaterService;
import org.jeecg.modules.water.service.ILwgyRelaxNbConnectionService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class SysnNbWaterDateJob implements Job {


    @Autowired
    private ILwgyJointWaterService lwgyJointWaterService;
    @Autowired
    private ILwgyJointWaterDailyService lwgyJointWaterDailyService;
    @Autowired
    private ILwgyJointWaterConfigurationService lwgyJointWaterConfigurationService;
    @Autowired
    private ILwgyRelaxNbConnectionService lwgyRelaxNbConnectionService;

    //水控-因收不到nb表推送（不知道为啥），所以写个定时器，每天去抄表；抄完了再算日用水量
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取前一天日期
        LocalDate yesterday = today.minusDays(1);

        // 获取前一天的凌晨时间（00:00:00）的字符串表示
        String yesterdayStartString = yesterday.atTime(LocalTime.MIN).format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        System.out.println("前一天凌晨时间：" + yesterdayStartString);
        // 获取前一天的晚上时间（23:59:59）的字符串表示
        String yesterdayEndString = yesterday.atTime(LocalTime.MAX).format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        System.out.println("前一天晚上时间：" + yesterdayEndString);


        //获取所有房间的设备通信码
        QueryWrapper<LwgyJointWaterConfiguration> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_type",0);//查询所有nb表
        List<LwgyJointWaterConfiguration> ljwc  = lwgyJointWaterConfigurationService.list(queryWrapper);

       // List<String> ispidList = ljwc.stream().map(obj ->  obj.getCommunicationCode()).collect(Collectors.toList());

        if(ljwc!=null && oConvertUtils.isNotEmpty(ljwc)) {
            List<LwgyJointWater> list = new ArrayList();
            List<LwgyJointWaterConfiguration> configlist = new ArrayList();
          //  for(String ispid:ispidList){
            for(LwgyJointWaterConfiguration wc:ljwc){
                String ispid = wc.getCommunicationCode();
                String json = lwgyRelaxNbConnectionService.getMessages(ispid, yesterday+" "+yesterdayStartString, yesterday+" "+yesterdayEndString);
                try {
                    log.info("收到一条抄表信息：" + json);
                    Gson gson = new Gson();
                    JsonObject jsonObject = gson.fromJson(json, JsonObject.class);

                    int code = jsonObject.get("code").getAsInt();
                    String msg = jsonObject.get("msg").getAsString();
                    JsonArray dataArray = jsonObject.getAsJsonArray("data");

                    System.out.println("Code: " + code);
                    System.out.println("Msg: " + msg);

                    for (JsonElement element : dataArray) {
                        LwgyJointWater water = new LwgyJointWater();
                        JsonObject dataObject = element.getAsJsonObject();
                        String ispids = dataObject.get("ispid").getAsString();
                        String curtime = dataObject.get("curtime").getAsString();

                        // 其他字段的解析方式类似，根据需要取出相应字段的值

                        JsonObject conterObject = dataObject.getAsJsonObject("conter");
                        String curnum = conterObject.get("curnum").getAsString();
                        String valvestate = conterObject.get("valvestate").getAsString();
                        String battery = conterObject.get("battery").getAsString();
                        String sensor = conterObject.get("sensor").getAsString();
                        String signal = conterObject.get("signal").getAsString();
                        String readperiod = conterObject.get("readperiod").getAsString();
                        String readstate = conterObject.get("readstate").getAsString();
                        String reversenum = conterObject.get("reversenum").getAsString();

                        System.out.println("ISP ID: " + ispids);
                        System.out.println("Current Time: " + curtime);
                        System.out.println("Curnum: " + curnum);
                        System.out.println("Valve State: " + valvestate);
                        // 可以继续解析其他字段
                        water.setIspid(ispids);
                        water.setCurtime(curtime);
                        water.setCurnum(curnum);
                        water.setValvestate(valvestate);
                        water.setBattery(battery);
                        water.setSensor(sensor);
                        water.setSignalstrength(signal);
                        water.setReadperiod(readperiod);
                        water.setReadstate(readstate);
                        water.setReversenum(reversenum);
                        water.setMeterReadingType("0");//手动抄表
                        list.add(water);
                        System.out.println("抄表电池状态："+battery);
                        System.out.println("设备管理电池状态："+wc.getBatteryStatus());
                        wc.setBatteryStatus(battery);
                        wc.setReading(curnum);
                        configlist.add(wc);

                    }


                } catch (Exception e1) {
                    e1.printStackTrace();
                }

            }
            System.out.println(list);
            lwgyJointWaterService.saveBatch(list);
            lwgyJointWaterConfigurationService.updateBatchById(configlist);


        }
    }
}
